<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Phira 管理员控制台</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            color: #ffffff;
            background-color: #0d0d0d;
            min-height: 100vh;
            overflow-x: hidden;
            position: relative;
        }
        .parallax-bg {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background-image: linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), url('https://webstatic.cn-nb1.rains3.com/5712%C3%973360.jpeg');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            z-index: 0;
        }
        header {
            position: fixed;
            top: 0;
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 1.5rem;
            backdrop-filter: blur(12px);
            background: rgba(0, 0, 0, 0.4);
            z-index: 1000;
            box-sizing: border-box;
        }
        .logo-nav-container { display: flex; align-items: center; flex: 1; }
        #logo-img { height: 32px; margin-right: 1.2rem; }
        .nav-links { display: flex; }
        .nav-links a {
            color: #eee;
            margin-right: 1.2rem;
            text-decoration: none;
            transition: 0.3s;
            font-size: 0.95rem;
        }
        .nav-links a:hover {
            color: #fff;
            text-shadow: 0 0 4px #fff;
        }
        .nav-links a.active {
            color: #a1e5ef;
            text-shadow: 0 0 8px #a1e5ef;
        }
        .user-section { display: flex; justify-content: flex-end; flex: 1; }
        .glass-button {
            display: flex; align-items: center;
            padding: 0.4rem 1rem;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 999px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            cursor: pointer;
            transition: all 0.3s ease;
            min-width: 100px;
        }
        .glass-button:hover {
            background: rgba(255, 255, 255, 0.15);
            transform: scale(1.05);
        }
        .user-info { display: flex; align-items: center; position: relative; cursor: pointer; width: 100%; }
        .username {
            margin-right: 0.8rem;
            font-size: 0.95rem;
            color: #eee;
            max-width: 120px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .user-avatar {
            width: 30px; height: 30px;
            border-radius: 50%; object-fit: cover;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        .dropdown-content {
            position: absolute;
            top: 100%; right: 0;
            background: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(12px);
            border-radius: 8px;
            padding: 0.8rem;
            min-width: 160px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.5);
            z-index: 1001;
            opacity: 0;
            visibility: hidden;
            transform: translateY(10px);
            transition: all 0.3s ease;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        .dropdown-content.show {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }
        .dropdown-content span {
            display: block;
            padding: 0.3rem 0.5rem;
            font-weight: bold;
            color: #a1e5ef;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 0.5rem;
        }
        .dropdown-content a {
            display: block;
            padding: 0.5rem;
            color: #eee;
            text-decoration: none;
            border-radius: 4px;
            transition: all 0.3s ease;
        }
        .dropdown-content a:hover {
            background: rgba(255, 255, 255, 0.1);
            color: #fff;
        }
        main {
            position: relative;
            z-index: 2;
            padding-top: 100px;
            display: flex;
            flex-direction: column;
            align-items: center;
            min-height: 100vh;
            padding-bottom: 50px;
        }
        .admin-container {
            transform-style: preserve-3d;
            transform: translateZ(20px);
            transition: transform 0.3s ease;
            animation: gentleSway 8s infinite ease-in-out;
            width: 95%;
            max-width: 1200px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 16px;
            backdrop-filter: blur(12px);
            padding: 2rem;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.2);
            margin: 1rem;
        }
        @keyframes gentleSway {
            0%, 100% { transform: translateZ(20px) rotateX(0.5deg) rotateY(0.5deg); }
            25% { transform: translateZ(20px) rotateX(-0.5deg) rotateY(-1deg); }
            50% { transform: translateZ(20px) rotateX(0.5deg) rotateY(1deg); }
            75% { transform: translateZ(20px) rotateX(-0.5deg) rotateY(0.5deg); }
        }
        .admin-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            padding-bottom: 1.5rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        .admin-title {
            font-size: 2rem;
            color: #a1e5ef;
        }
        .user-count {
            background: rgba(161,229,239,0.2);
            color: #a1e5ef;
            padding: 0.5rem 1rem;
            border-radius: 999px;
            font-weight: bold;
        }
        .cards-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
        }
        .glass-card {
            backdrop-filter: blur(12px);
            background: rgba(30, 30, 42, 0.25);
            border-radius: 16px;
            padding: 1.5rem;
            border: 1px solid rgba(255, 255, 255, 0.15);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            transition: transform 0.3s ease;
        }
        .glass-card:hover { transform: translateY(-5px); }
        .glass-card h1, .glass-card h2 { margin-bottom: 1.2rem; font-weight: 500; }
        .status-card { display: flex; flex-direction: column; align-items: center; }
        .status-dot {
            width: 24px; height: 24px; border-radius: 50%; background: #666; display: inline-block; margin-right: 10px;
        }
        #serverStatusContainer { display: flex; align-items: center; margin-bottom: 1.5rem; }
        .control-buttons { display: flex; justify-content: space-between; gap: 1rem; }
        .glass-button-control {
            padding: 0.8rem 1.5rem;
            backdrop-filter: blur(5px);
            background: rgba(80, 90, 200, 0.25);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            min-width: 100px;
            text-align: center;
        }
        .glass-button-control:hover {
            background: rgba(100, 110, 220, 0.35);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        .cmd-input { display: flex; gap: 10px; }
        #customCommand {
            flex: 1;
            padding: 0.8rem;
            background: rgba(30, 30, 42, 0.4);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            color: white;
        }
        #customCommand::placeholder { color: rgba(255, 255, 255, 0.5); }
        .output-card { grid-column: 1 / -1; }
        #commandOutput {
            min-height: 200px;
            max-height: 400px;
            overflow: auto;
            padding: 1rem;
            background: rgba(20, 20, 30, 0.4);
            border-radius: 8px;
            font-family: 'Consolas', 'Courier New', monospace;
            white-space: pre-wrap;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        .status-online { background-color: #4caf50; }
        .status-offline { background-color: #f44336; }
        .status-loading { background-color: #ffc107; }
        .message {
            padding: 0.8rem;
            border-radius: 8px;
            margin: 1rem 0;
            text-align: center;
            display: none;
            backdrop-filter: blur(6px);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        .message-success { background: rgba(0, 200, 0, 0.2); color: #0f0; }
        .message-error { background: rgba(200, 0, 0, 0.2); color: #f33; }
        @media (max-width: 768px) {
            header { flex-wrap: wrap; }
            .logo-nav-container { flex: 0 0 100%; margin-bottom: 0.5rem; }
            .user-section { flex: 0 0 100%; justify-content: flex-end; }
            .nav-links a { margin-right: 1rem; }
            .username { max-width: 80px; }
            .control-buttons { flex-direction: column; }
            .cards-container { grid-template-columns: 1fr; }
        }
        /* 用户管理表格样式 */
        .table-container { margin-top: 2rem; }
        .users-table {
            width: 100%; border-collapse: collapse; margin-bottom: 2rem;
        }
        .users-table th {
            text-align: left; padding: 1rem;
            background: rgba(161,229,239,0.1);
            color: #a1e5ef;
            font-weight: 500;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        .users-table td {
            padding: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }
        .user-row:hover { background: rgba(255, 255, 255, 0.03); }
        .user-avatar-small {
            width: 40px; height: 40px; border-radius: 50%; object-fit: cover; border: 1px solid rgba(255, 255, 255, 0.2);
        }
        .user-select { width: 20px; height: 20px; cursor: pointer; }
        .badge {
            display: inline-block; padding: 0.3rem 0.8rem; border-radius: 999px; font-size: 0.85rem; margin-right: 0.5rem;
            background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2);
        }
        .badge-admin { background: rgba(161,229,239,0.2); color: #a1e5ef; }
        .badge-dev { background: rgba(0, 204, 255, 0.2); color: #00ccff; }
        .actions-cell { display: flex; gap: 0.5rem; }
        .action-btn {
            padding: 0.4rem 0.8rem; border-radius: 6px; font-size: 0.9rem; cursor: pointer; transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.1); color: white; border: 1px solid rgba(255, 255, 255, 0.2);
        }
        .action-btn:hover { background: rgba(255, 255, 255, 0.15); }
        .btn-edit { background: rgba(0, 150, 255, 0.2); color: #0096ff; }
        .filters { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
        .filter-input {
            flex: 1; min-width: 250px; padding: 0.8rem 1rem;
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px; color: #fff; font-size: 1rem; outline: none;
        }
        .filter-input:focus {
            border-color: rgba(255, 255, 255, 0.4);
            box-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
        }
        .batch-actions { display: flex; gap: 1rem; margin-bottom: 2rem; flex-wrap: wrap; }
        .batch-form { display: flex; gap: 1rem; align-items: center; flex-wrap: wrap; }
        .batch-label { color: #ddd; font-size: 0.9rem; }
        .batch-select {
            padding: 0.6rem 1rem; background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.2); border-radius: 8px; color: #fff; min-width: 150px;
        }
        .btn { padding: 0.8rem 1.5rem; border-radius: 8px; border: none; font-size: 1rem; cursor: pointer; transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(10px); color: white; font-weight: 500; display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem; border: 1px solid rgba(255, 255, 255, 0.2); }
        .btn:hover { background: rgba(255, 255, 255, 0.15); transform: translateY(-2px); }
        .btn-outline { background: transparent; border: 1px solid rgba(255, 255, 255, 0.2); color: #ddd; }
        .btn-outline:hover { background: rgba(255, 255, 255, 0.1); }
    </style>
</head>
<body>
    <div class="parallax-bg"></div>
    <header>
        <div class="logo-nav-container">
            <img id="logo-img" src="logo.png" alt="logo" />
            <div class="nav-links">
                <a href="index.html">主页</a>
                <a href="rooms.html">房间列表</a>
                <a href="account.html">账号管理</a>
                <a href="#" class="active">管理员控制台</a>
            </div>
        </div>
        <div class="user-section">
            <div id="avatar-container" class="glass-button">
                <div class="user-info" onclick="toggleDropdown()">
                    <span class="username" id="username-display"></span>
                    <img id="user-avatar" src="" alt="用户头像" class="user-avatar" />
                </div>
                <div class="dropdown-content" id="user-dropdown">
                    <span id="dropdown-username"></span>
                    <a id="phira-profile-link" target="_blank">我的Phira账号</a>
                    <a href="account.html">账号管理</a>
                    <a href="javascript:void(0)" onclick="logout()">退出登录</a>
                </div>
            </div>
        </div>
    </header>
    <main>
        <div class="admin-container">
            <div class="admin-header">
                <h1 class="admin-title">管理员控制台</h1>
                <div class="user-count">用户总数: <span id="total-users">0</span></div>
            </div>
            <div class="filters">
                <input type="text" class="filter-input" id="search-name" placeholder="搜索用户名..." />
                <input type="text" class="filter-input" id="search-phira" placeholder="搜索Phira ID..." />
                <select class="filter-input" id="filter-admin">
                    <option value="all">所有管理员状态</option>
                    <option value="yes">管理员</option>
                    <option value="no">非管理员</option>
                </select>
                <select class="filter-input" id="filter-dev">
                    <option value="all">所有开发者状态</option>
                    <option value="yes">开发者</option>
                    <option value="no">非开发者</option>
                </select>
            </div>
            <div class="batch-actions">
                <div class="batch-form">
                    <span class="batch-label">批量操作:</span>
                    <select class="batch-select" id="batch-action">
                        <option value="set_admin">设为管理员</option>
                        <option value="remove_admin">取消管理员</option>
                        <option value="set_dev">设为开发者</option>
                        <option value="remove_dev">取消开发者</option>
                    </select>
                    <button class="btn" onclick="applyBatchAction()">应用</button>
                    <button class="btn btn-outline" onclick="selectAllUsers()">全选</button>
                    <button class="btn btn-outline" onclick="deselectAllUsers()">取消全选</button>
                </div>
            </div>
            <div id="admin-message" class="message"></div>
            <div class="table-container">
                <table class="users-table">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="select-all" class="user-select" /></th>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>头像</th>
                            <th>Phira ID</th>
                            <th>Phira 用户名</th>
                            <th>RKS</th>
                            <th>权限</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="users-table-body">
                        <!-- 用户数据将通过JavaScript填充 -->
                    </tbody>
                </table>
            </div>
            <div class="cards-container">
                <div class="glass-card status-card">
                    <h2>服务器状态</h2>
                    <div id="serverStatusContainer">
                        <div class="status-dot" id="serverStatusDot"></div>
                        <span id="serverStatus">检测中...</span>
                    </div>
                    <div style="display: flex; justify-content: center; width: 100%;">
                        <button id="refreshStatus" class="glass-button-control">刷新状态</button>
                    </div>
                </div>
                <div class="glass-card status-card">
                    <h2>API状态</h2>
                    <div id="apiStatusContainer">
                        <div class="status-dot" id="apiStatusDot"></div>
                        <span id="apiStatus">检测中...</span>
                    </div>
                </div>
                <div class="glass-card control-card">
                    <h2>服务控制</h2>
                    <div class="control-buttons">
                        <button id="startServer" class="glass-button-control">启动</button>
                        <button id="restartServer" class="glass-button-control">重启</button>
                        <button id="stopServer" class="glass-button-control">关闭</button>
                    </div>
                </div>
                <div class="glass-card custom-cmd-card">
                    <h2>自定义命令</h2>
                    <div class="cmd-input">
                        <input type="text" id="customCommand" placeholder="输入命令...">
                        <button id="executeCmd" class="glass-button-control">执行</button>
                    </div>
                </div>
                <div class="glass-card output-card">
                    <h2>命令执行结果</h2>
                    <pre id="commandOutput">等待命令执行...</pre>
                </div>
            </div>
        </div>
    </main>
    <!-- 编辑用户模态框 -->
    <div id="edit-modal" class="modal" style="display:none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">编辑用户信息</h3>
                <button class="close-modal" onclick="closeEditModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div id="edit-message" class="message"></div>
                <input type="hidden" id="edit-user-id" />
                <div class="form-group">
                    <label class="form-label">用户名</label>
                    <input type="text" class="form-input" id="edit-username" />
                </div>
                <div class="form-group">
                    <label class="form-label">密码</label>
                    <div class="password-display" id="password-display">************</div>
                    <button class="reveal-btn" onclick="togglePasswordDisplay()">显示/隐藏密码</button>
                    <input type="password" class="form-input" id="edit-password" placeholder="输入新密码" style="margin-top: 0.5rem;" />
                </div>
                <div class="form-group">
                    <label class="form-label">Phira ID</label>
                    <input type="text" class="form-input" id="edit-phira-id" />
                </div>
                <div class="form-row">
                    <div class="form-col">
                        <label class="form-label">管理员状态</label>
                        <select class="form-input" id="edit-admin">
                            <option value="no">否</option>
                            <option value="yes">是</option>
                        </select>
                    </div>
                    <div class="form-col">
                        <label class="form-label">开发者权限</label>
                        <select class="form-input" id="edit-dev">
                            <option value="no">否</option>
                            <option value="yes">是</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline" onclick="closeEditModal()">取消</button>
                <button class="btn" onclick="saveUserChanges()">保存更改</button>
            </div>
        </div>
    </div>
    <script>
        // 全局变量
        let currentUser = null;
        let allUsers = [];
        let adminPassword = '';
        let isSuperAdmin = false;
        const API_BASE_URL = 'https://phira.htadiy.cc/postadmin';
        const API_PWD1 = 'nb3502022';
        const API_PWD2 = '2022350';
        const API_PWD3 = 'nb3502022outlookcom';
        const STATUS_COLORS = {
            online: '#4caf50',
            offline: '#f44336',
            loading: '#ffc107',
            unknown: '#9e9e9e'
        };
        const SERVER_COMMANDS = {
            start: 'bash /root/start.sh',
            restart: 'bash /root/stop.sh && bash /root/start.sh',
            stop: 'bash /root/stop.sh',
            check: 'bash /root/check.sh'
        };

        document.addEventListener('DOMContentLoaded', () => {
            const savedUser = localStorage.getItem('user');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
                if (currentUser.admin !== "yes") {
                    showAdminMessage('您不是管理员，无法访问此页面', false);
                    setTimeout(() => {
                        window.location.href = 'index.html';
                    }, 2000);
                    return;
                }
                updateUserDisplay();
                showAdminPasswordModal();
                checkAllStatus();
            } else {
                showAdminMessage('请先登录', false);
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 1500);
            }
            document.getElementById('refreshStatus').addEventListener('click', checkAllStatus);
            document.getElementById('startServer').addEventListener('click', () => executeServerCommand('start'));
            document.getElementById('restartServer').addEventListener('click', () => executeServerCommand('restart'));
            document.getElementById('stopServer').addEventListener('click', () => executeServerCommand('stop'));
            document.getElementById('executeCmd').addEventListener('click', executeCustomCommand);
            document.getElementById('customCommand').addEventListener('keyup', (e) => {
                if (e.key === 'Enter') executeCustomCommand();
            });
            document.getElementById('search-name').addEventListener('input', () => renderUsersTable(allUsers));
            document.getElementById('search-phira').addEventListener('input', () => renderUsersTable(allUsers));
            document.getElementById('filter-admin').addEventListener('change', () => renderUsersTable(allUsers));
            document.getElementById('filter-dev').addEventListener('change', () => renderUsersTable(allUsers));
            document.getElementById('select-all').addEventListener('change', function() {
                document.querySelectorAll('.user-select').forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });
        });

        // 用户信息显示
        function updateUserDisplay() {
            if (currentUser) {
                document.getElementById('username-display').textContent = currentUser.name;
                document.getElementById('user-avatar').src = currentUser.image_url || 'https://phira.moe/assets/user-6212ee95.png';
                document.getElementById('dropdown-username').textContent = currentUser.name;
                document.getElementById('phira-profile-link').href = `https://phira.5wyxi.com/user/${currentUser.phira_id}`;
            }
        }
        function toggleDropdown() {
            const dropdown = document.getElementById('user-dropdown');
            if (dropdown) {
                dropdown.classList.toggle('show');
            }
        }
        function logout() {
            localStorage.removeItem('user');
            window.location.href = 'index.html';
        }

        // 管理员密码模态框
        function showAdminPasswordModal() {
            document.getElementById('admin-password-modal').style.display = 'flex';
        }
        function closeAdminPasswordModal() {
            window.location.href = 'account.html';
        }
        function verifyAdminPassword() {
            const password = document.getElementById('admin-password-input').value;
            const messageElement = document.getElementById('admin-password-message');
            if (!password) {
                messageElement.textContent = '请输入管理员密码';
                messageElement.className = 'message message-error';
                messageElement.style.display = 'block';
                return;
            }
            fetch('/admin/users', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ password })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    adminPassword = password;
                    isSuperAdmin = data.users.some(u => u.password);
                    document.getElementById('admin-password-modal').style.display = 'none';
                    loadAllUsers();
                } else {
                    messageElement.textContent = data.message || '密码验证失败';
                    messageElement.className = 'message message-error';
                    messageElement.style.display = 'block';
                }
            })
            .catch(error => {
                messageElement.textContent = '网络错误，请重试';
                messageElement.className = 'message message-error';
                messageElement.style.display = 'block';
            });
        }

        // 用户管理
        function loadAllUsers() {
            fetch('/admin/users', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ password: adminPassword })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    allUsers = data.users;
                    document.getElementById('total-users').textContent = allUsers.length;
                    renderUsersTable(allUsers);
                } else {
                    showAdminMessage(data.message || '加载用户数据失败', false);
                }
            })
            .catch(error => {
                showAdminMessage('网络错误，请重试', false);
            });
        }
        function renderUsersTable(users) {
            const tableBody = document.getElementById('users-table-body');
            tableBody.innerHTML = '';
            const searchName = document.getElementById('search-name').value.toLowerCase();
            const searchPhira = document.getElementById('search-phira').value.toLowerCase();
            const filterAdmin = document.getElementById('filter-admin').value;
            const filterDev = document.getElementById('filter-dev').value;
            const filteredUsers = users.filter(user => {
                const nameMatch = user.name.toLowerCase().includes(searchName);
                const phiraMatch = user.phira_id.toLowerCase().includes(searchPhira);
                const adminMatch = filterAdmin === 'all' || user.admin === filterAdmin;
                const devMatch = filterDev === 'all' || user.dev === filterDev;
                return nameMatch && phiraMatch && adminMatch && devMatch;
            });
            filteredUsers.forEach(user => {
                const row = document.createElement('tr');
                row.className = 'user-row';
                row.innerHTML = `
                  <td><input type="checkbox" class="user-select" data-id="${user.id}" /></td>
                  <td>${user.id}</td>
                  <td>${user.name}</td>
                  <td><img src="${user.image_url || 'https://phira.moe/assets/user-6212ee95.png'}" class="user-avatar-small" /></td>
                  <td>${user.phira_id}</td>
                  <td>${user.phira_name}</td>
                  <td>${user.phira_rks ? parseFloat(user.phira_rks).toFixed(2) : '0.00'}</td>
                  <td>
                    ${user.admin === 'yes' ? '<span class="badge badge-admin">管理员</span>' : ''}
                    ${user.dev === 'yes' ? '<span class="badge badge-dev">开发者</span>' : ''}
                  </td>
                  <td class="actions-cell">
                    <button class="action-btn btn-edit" onclick="openEditModal(${user.id})">编辑</button>
                  </td>
                `;
                tableBody.appendChild(row);
            });
        }
        function openEditModal(userId) {
            const user = allUsers.find(u => u.id === userId);
            if (!user) return;
            document.getElementById('edit-user-id').value = user.id;
            document.getElementById('edit-username').value = user.name;
            document.getElementById('edit-phira-id').value = user.phira_id;
            document.getElementById('edit-admin').value = user.admin;
            document.getElementById('edit-dev').value = user.dev;
            document.getElementById('password-display').dataset.original = user.password;
            document.getElementById('edit-message').style.display = 'none';
            document.getElementById('edit-modal').style.display = 'flex';
        }
        function closeEditModal() {
            document.getElementById('edit-modal').style.display = 'none';
        }
        function togglePasswordDisplay() {
            const display = document.getElementById('password-display');
            if (display.textContent === '************') {
                display.textContent = display.dataset.original;
            } else {
                display.textContent = '************';
            }
        }
        function saveUserChanges() {
            const userId = parseInt(document.getElementById('edit-user-id').value);
            const username = document.getElementById('edit-username').value;
            const password = document.getElementById('edit-password').value;
            const phiraId = document.getElementById('edit-phira-id').value;
            const admin = document.getElementById('edit-admin').value;
            const dev = document.getElementById('edit-dev').value;
            const changes = { name: username, admin, dev };
            if (phiraId) changes.phira_id = phiraId;
            if (password) changes.password = password;
            fetch('/admin/update', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ password: adminPassword, user_id: userId, changes })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showEditMessage('用户信息更新成功', true);
                    setTimeout(() => {
                        closeEditModal();
                        loadAllUsers();
                    }, 1500);
                } else {
                    showEditMessage(data.message || '更新失败', false);
                }
            })
            .catch(error => {
                showEditMessage('网络错误，请重试', false);
            });
        }
        function showEditMessage(message, isSuccess) {
            const messageElement = document.getElementById('edit-message');
            messageElement.textContent = message;
            messageElement.className = `message ${isSuccess ? 'message-success' : 'message-error'}`;
            messageElement.style.display = 'block';
        }
        function selectAllUsers() {
            document.querySelectorAll('.user-select').forEach(checkbox => {
                checkbox.checked = true;
            });
        }
        function deselectAllUsers() {
            document.querySelectorAll('.user-select').forEach(checkbox => {
                checkbox.checked = false;
            });
        }
        function applyBatchAction() {
            const action = document.getElementById('batch-action').value;
            const selectedUserIds = [];
            document.querySelectorAll('.user-select:checked').forEach(checkbox => {
                if (checkbox.id !== 'select-all') {
                    selectedUserIds.push(parseInt(checkbox.dataset.id));
                }
            });
            if (selectedUserIds.length === 0) {
                showAdminMessage('请选择至少一个用户', false);
                return;
            }
            let changes = {};
            switch (action) {
                case 'set_admin': changes.admin = 'yes'; break;
                case 'remove_admin': changes.admin = 'no'; break;
                case 'set_dev': changes.dev = 'yes'; break;
                case 'remove_dev': changes.dev = 'no'; break;
            }
            fetch('/admin/batch-update', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ password: adminPassword, user_ids: selectedUserIds, changes })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    const successCount = data.results.filter(r => r.status === 'success').length;
                    const errorCount = data.results.filter(r => r.status === 'error').length;
                    if (errorCount === 0) {
                        showAdminMessage(`成功更新 ${successCount} 个用户`, true);
                    } else {
                        showAdminMessage(`成功更新 ${successCount} 个用户，失败 ${errorCount} 个`, false);
                    }
                    loadAllUsers();
                } else {
                    showAdminMessage(data.message || '批量更新失败', false);
                }
            })
            .catch(error => {
                showAdminMessage('网络错误，请重试', false);
            });
        }

        // 管理员消息
        function showAdminMessage(message, isSuccess) {
            const messageElement = document.getElementById('admin-message');
            messageElement.textContent = message;
            messageElement.className = `message ${isSuccess ? 'message-success' : 'message-error'}`;
            messageElement.style.display = 'block';
            setTimeout(() => {
                messageElement.style.display = 'none';
            }, 5000);
        }

        // 服务器与API状态
        function checkAllStatus() {
            checkApiStatus();
            checkServerStatus();
        }
        function checkApiStatus() {
            updateApiStatus('检测中...', 'loading');
            fetch('https://phira.htadiy.cc/roomsjson', {
                method: 'GET',
                cache: 'no-store'
            })
            .then(response => {
                if (!response.ok) throw new Error('API响应错误');
                return response.json();
            })
            .then(data => {
                if (Array.isArray(data) && data.length > 0) {
                    updateApiStatus('在线', 'online');
                } else {
                    updateApiStatus('在线', 'online');
                }
            })
            .catch(() => {
                updateApiStatus('离线', 'offline');
            });
        }
        function updateApiStatus(text, status) {
            const apiStatusText = document.getElementById('apiStatus');
            const apiStatusDot = document.getElementById('apiStatusDot');
            apiStatusText.textContent = text;
            apiStatusDot.style.backgroundColor = STATUS_COLORS[status] || STATUS_COLORS.unknown;
        }
        function checkServerStatus() {
            updateServerStatus('检测中...', 'loading');
            sendAuthenticatedCommand('custom', SERVER_COMMANDS.check)
                .then(response => {
                    if (!response.ok) throw new Error('服务器响应错误');
                    return response.json();
                })
                .then(data => {
                    if (data.status === "success") {
                        updateServerStatus('运行中', 'online');
                    } else {
                        updateServerStatus('已停止', 'offline');
                    }
                })
                .catch(() => {
                    updateServerStatus('已停止', 'offline');
                });
        }
        function updateServerStatus(text, status) {
            const serverStatusText = document.getElementById('serverStatus');
            const serverStatusDot = document.getElementById('serverStatusDot');
            serverStatusText.textContent = text;
            serverStatusDot.style.backgroundColor = STATUS_COLORS[status] || STATUS_COLORS.unknown;
        }
        function sendAuthenticatedCommand(command, customCmd = null) {
            const params = new URLSearchParams();
            params.append('pwd1', API_PWD1);
            params.append('pwd2', API_PWD2);
            params.append('pwd3', API_PWD3);
            if (customCmd) {
                params.append('cmd', 'custom');
                params.append('custom_cmd', customCmd);
            } else {
                params.append('cmd', command);
            }
            return fetch(`${API_BASE_URL}/execute`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: params
            });
        }
        function executeServerCommand(commandType) {
            if (!SERVER_COMMANDS[commandType]) return;
            const commandOutput = document.getElementById('commandOutput');
            commandOutput.textContent = '执行中...';
            sendAuthenticatedCommand('custom', SERVER_COMMANDS[commandType])
                .then(response => {
                    if (response.ok) {
                        return response.text();
                    } else {
                        throw new Error('服务器响应错误');
                    }
                })
                .then(data => {
                    commandOutput.textContent = data;
                    setTimeout(() => {
                        checkServerStatus();
                    }, 2000);
                })
                .catch(error => {
                    commandOutput.textContent = `错误: ${error.message || '执行失败'}`;
                });
        }
        function executeCustomCommand() {
            const command = document.getElementById('customCommand').value.trim();
            const commandOutput = document.getElementById('commandOutput');
            if (!command) {
                commandOutput.textContent = '错误：请输入命令';
                return;
            }
            commandOutput.textContent = '执行中...';
            sendAuthenticatedCommand('custom', command)
                .then(response => {
                    if (response.ok) {
                        return response.text();
                    } else {
                        throw new Error('服务器响应错误');
                    }
                })
                .then(data => {
                    commandOutput.textContent = data;
                    document.getElementById('customCommand').value = '';
                })
                .catch(error => {
                    commandOutput.textContent = `错误: ${error.message || '执行失败'}`;
                });
        }
    </script>
</body>
</html>
